package cn.uestc.labhms.modules.hms.service.impl;

import cn.uestc.labhms.modules.hms.dao.HmsCommonConditionDao;
import cn.uestc.labhms.modules.hms.dao.HmsChiEngDao;
import cn.uestc.labhms.modules.hms.entity.HmsCommonConditionEntity;
import cn.uestc.labhms.modules.hms.entity.Vo.CommonConditionVo;
import cn.uestc.labhms.modules.hms.exception.HMSException;
import cn.uestc.labhms.modules.hms.service.ConditionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Service
public class ConditionServiceImpl implements ConditionService {
    @Autowired
    private HmsCommonConditionDao hmsCommonConditionDao;
    @Autowired
    private HmsChiEngDao hmsChiEngDao;

    @Override
    public CommonConditionVo getAllConditions() {
        CommonConditionVo commonConditionVo = new CommonConditionVo();
        List<String> distinctFieldC = hmsChiEngDao.getDistinctFieldC();
        if (ObjectUtils.isEmpty(distinctFieldC)) {
            throw new HMSException("当前查询条件为空");
        }
        commonConditionVo.setConditionsCN(distinctFieldC);
        return commonConditionVo;
    }

    @Override
    public CommonConditionVo getCommonConditions() {
        CommonConditionVo commonConditionVo = new CommonConditionVo();
        List<String> distinctFieldC = hmsCommonConditionDao.getCommonFiled();
        if (ObjectUtils.isEmpty(distinctFieldC)) {
            throw new HMSException("当前查询条件为空");
        }
        commonConditionVo.setConditionsCN(distinctFieldC);
        return commonConditionVo;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void setCommonConditions(List<String> conditions) {
        hmsCommonConditionDao.clearTable();
        HmsCommonConditionEntity newCommonConditionEntity = new HmsCommonConditionEntity();
        for (String chField : conditions) {
            String enField = hmsCommonConditionDao.getFieldEnByCh(chField);
            if (ObjectUtils.isEmpty(enField)) {
                throw new HMSException("当前中文查询字段没有对应英文字段");
            }
            newCommonConditionEntity.setFieldCh(chField);
            newCommonConditionEntity.setFieldEn(enField);
            if (hmsCommonConditionDao.setCommonFiled(newCommonConditionEntity) == 0) {
                throw new HMSException("插入数据失败，请查看字段:" + chField);
            }
        }
    }
}
